package controller.user;

import com.alibaba.fastjson.JSON;
import entity.ResultVo;
import entity.User;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/login")
public class UserLoginController extends HttpServlet {
    //controller调用service
    private UserService userService = new UserServiceImpl();

    /**
     * @param req 封装所有的请求的头信息
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置文档的类型
        resp.setContentType("text/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        //根据请求的key的名称来获取参数值
        //前端传过来的数据
        String username = req.getParameter("username");//此处的username就是url中的key
        String password = req.getParameter("password");
        //System.out.println(username+":"+password);

        //根据username进行查询
        //如果顺利查到,则返回user对象
        //如果查询不到,则返回null
        User user = userService.login(username);

        //1. 判断user是否存在
        if(user!=null){
            //能执行到此处,说明user是存在的.

            //判断密码是否是ok
            //db中的行记录的密码和页面传过来的密码进行比较
            if(user.getPassword().equals(password)){ // 密码是ok
                ResultVo resultVo = new ResultVo("200","登录成功");
                out.print(JSON.toJSONString(resultVo));
            }else{
                //密码是错误的.
                ResultVo resultVo = new ResultVo("500","sorry,密码是错误的!");
                out.print(JSON.toJSONString(resultVo));
            }
        }else{
            //user为空...  user不存在
            ResultVo resultVo = new ResultVo("404","sorry,用户不存在!");
            //将json对象转换成json字符串
            String resultVoStr = JSON.toJSONString(resultVo);
            //返回出去的json字符串会自动封装到$.post的第三个参数的函数的res中
            out.print(resultVoStr);
        }
    }
}